<template>
  <div>
    <header-toobar>
      <a-button style="margin-left: 8px;" size="small" type="primary" icon="share-alt"
                @click="() =>{this.openFlowNodeModel()}">流程分配
      </a-button>
      <a-button style="margin-left: 8px;" size="small" type="primary" icon="calendar"
                @click="() =>{this.openRoleRouterFuncModel()}">资源分配
      </a-button>
      <a-button style="margin-left: 8px;" size="small" type="primary" icon="solution"
                @click="() =>{this.openRoleOrgModel()}">组织分配
      </a-button>
      <a-button style="margin-left: 8px;" size="small" type="primary" icon="team"
                @click="() =>{this.openRoleUserModel()}">用户分配
      </a-button>
      <a-button style="margin-left: 8px" size="small" type="primary" icon="user-add" @click="() =>{this.addRole()}">
        创建角色
      </a-button>
      <a-button style="margin-left: 8px;" size="small" type="primary" icon="edit" @click="() =>{this.editRole()}">编辑
      </a-button>
      <a-button style="margin-left: 8px" size="small" type="danger" icon="delete" @click="() =>{this.deleteRole()}">删除
      </a-button>
    </header-toobar>
    <zh-row :span="24" :gutter="[16,16]">
      <zh-col>
        <zh-card title="查询条件">
          <zh-form ref="roleFrom" :model="queryParam">
            <zh-input prop="roleName" label="角色名称" placeholder="支持模糊查询" v-model="queryParam.roleName"></zh-input>
            <zh-input prop="roleTypes" type="select" label="角色类型" mode="multiple" placeholder="支持多选" allowClear
                      :options="dictData.roleType" v-model="queryParam.roleTypes"></zh-input>
            <template v-if="advanced">
              <zh-input prop="status" type="select" label="状态" placeholder="单选" allowClear :options="statusData"
                        v-model="queryParam.status"></zh-input>
            </template>
            <zh-form-query v-model="advanced" @queryClick="findRoleListBtn"></zh-form-query>
          </zh-form>
        </zh-card>
      </zh-col>
      <zh-col>
        <zh-table :shadow="true" ref="roleTable" title="角色列表" row-id="roleId" :url="tableUrl" :columns="tableColumn"
                  @radio-change="radioChangeEvent" :radio-config="{ trigger: 'row'}" :disabled="false">
          <template #status_edit="{ row }">
            <zh-input type="switch" :formflag="false" v-model="row.status" @change="onStatusChange(row)"
                      checked-children="启用" un-checked-children="禁用"></zh-input>
          </template>
        </zh-table>
      </zh-col>
    </zh-row>


    <a-modal
        :title="modalTitle"
        centered
        style="top: 10px;"
        width="50%"
        destroyOnClose
        v-model="visible"
        @ok="saveRole"
        @cancel="cancelRole"
        cancelText="关闭"
        okText="保存"
    >
      <role-form ref="rolePage" :roleInfo="selectRow"/>
    </a-modal>
    <a-modal
        title="用户授权"
        style="top: 10px;"
        centered
        width="85%"
        destroyOnClose
        v-model="roleUserVisible"
    >
      <template slot="footer">
        <a-button @click="closeRoleUser">
          关闭
        </a-button>
        <a-button type="primary" @click="saveUser" :disabled="saveUserDisable">
          授权
        </a-button>
        <a-button type="danger" @click="deleteUser" :disabled="deleteUserDisable">
          取消授权
        </a-button>
      </template>
      <role-user-form ref="roleUserPage" @roleUserBtn="setRoleUserBtn" :roleInfo="selectRow"/>
    </a-modal>
    <a-modal
        title="组织授权"
        centered
        style="top: 10px;"
        width="450px"
        destroyOnClose
        v-model="roleOrgVisible"
        @ok="saveOrg"
        cancelText="关闭"
        okText="保存"
    >
      <org-tree-form ref="orgTreePage" :roleId="roleId"/>
    </a-modal>
    <a-modal
        title="资源授权"
        centered
        style="top: 10px;"
        width="450px"
        destroyOnClose
        v-model="roleRouterFuncVisible"
        @ok="saveRouterFunc"
        cancelText="关闭"
        okText="保存"
    >
      <router-func-tree-form ref="routerFuncTreePage" :roleId="roleId"/>
    </a-modal>

    <a-modal
        title="流程授权"
        centered
        style="top: 10px;"
        width="450px"
        destroyOnClose
        v-model="flowNodeVisible"
        @ok="saveFlowNode"
        cancelText="关闭"
        okText="保存"
    >
      <flow-node-tree-form ref="flowNodeTreePage" :roleId="roleId"/>
    </a-modal>

  </div>
</template>

<script>
import {
  addRole,
  deleteRole,
  deleteRoleUser,
  editRole,
  editRoleStatus,
  getBatchDict,
  getRoleList,
  saveRoleFlowNode,
  saveRoleOrg,
  saveRoleRouterFunc,
  saveRoleUser
} from "@/services/system/api"
import HeaderToobar from '@/components/HeaderToobar'
import modal from 'ant-design-vue/es/modal'
import RoleForm from '@/pages/system/form/RoleForm'
import RoleUserForm from '@/pages/system/form/RoleUserForm'
import OrgTreeForm from '@/pages/system/form/OrgTreeForm'
import RouterFuncTreeForm from '@/pages/system/form/RouterFuncTreeForm'

import FlowNodeTreeForm from '@/pages/system/form/FlowNodeTreeForm'
import moment from 'moment'

const flagMap = {
  0: {
    status: 'default',
    text: '否'
  },
  1: {
    status: 'processing',
    text: '是'
  }
}
export default {
  name: 'RoleManager',
  components: {
    HeaderToobar,
    RoleForm,
    RoleUserForm,
    OrgTreeForm,
    RouterFuncTreeForm,
    FlowNodeTreeForm
  },
  data() {
    return {
      description: '角色管理',
      dictData: {},
      visible: false,
      form: null,
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      loading: false,
      tablePage: {
        total: 0,
        currentPage: 1,
        pageNum: 1,
        pageSize: 20
      },
      tableColumn: [
        {
          type: 'radio', width: 40, fixed: 'left', align: 'center', slots: {
            header: () => {
              return [<a-tooltip placement="top" title="取消选择">
                <a-icon type="stop" theme="twoTone" onClick={this.clearRadioRowEevnt}/>
              </a-tooltip>]
            }
          }
        },
        {type: 'seq', width: 80, fixed: 'left', align: 'center', title: '序号'},
        {field: 'roleId', title: '角色Id', fixed: 'left', visible: false, align: 'center', width: 150},
        {field: 'roleName', title: '角色名称', align: 'center', fixed: 'left', width: 350},
        {
          field: 'fixed', title: '是否可编辑', align: 'center', fixed: 'left', width: 120, slots: {
            default: ({row}) => {
              return this.setFlag(row)
            }
          }
        },
        {
          field: 'status', title: '状态', align: 'center', editRender: {}, slots: {
            // 使用插槽模板渲染
            default: 'status_edit',
            edit:'status_edit',
          }, width: 80
        },
        {field: 'parentId', title: '父角色Id', visible: false, align: 'center', width: 200},
        {field: 'roleType', title: '角色类型', visible: false, align: 'center', width: 100},
        {field: 'roleTypeName', title: '角色类型', align: 'center', width: 150},
        {field: 'remarks', title: '备注', align: 'center', showOverflow: true, width: "auto"}
      ],
      tableData: [],
      selectRow: null,
      modalTitle: '操作',
      roleUserVisible: false,
      saveUserDisable: false,
      deleteUserDisable: true,
      roleOrgVisible: false,
      roleId: null,
      roleRouterFuncVisible: false,
      flowNodeVisible: false,
      statusData: [{dictKey: '1', dictValue: '启用'}, {dictKey: '0', dictValue: '禁用'}],
      tableUrl: getRoleList
    }
  },

  created() {
    // 数据初始化
    // 数据字典初始化
    const params = {}
    params.dictFields = 'roleType'
    this.$http.post(getBatchDict, params).then(res => {
      this.dictData = res.result
    })

  },
  mounted() {
    this.findRoleList()
  },
  methods: {

    moment,
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    setFlag(row) {
      const text = flagMap[row.fixed].text
      const status = flagMap[row.fixed].status
      if (text) {
        return [<a-badge status={status} text={text}/>]
      } else {
        return row.fixed
      }
    },
    radioChangeEvent({row}) {
      this.roleId = row.roleId
      this.selectRow = row
      console.log('单选事件')
    },
    clearRadioRowEevnt() {
      this.selectRow = null
      this.$refs.roleTable.clearRadioRow()
    },
    handlePageChange({currentPage, pageSize}) {
      this.tablePage.pageNum = currentPage
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.findRoleList()
    },
    findRoleListBtn() {
      this.findRoleList()
    },
    findRoleList() {
      this.$refs.roleTable.query(this.queryParam)
    },
    refreshList() {
      this.$refs.roleTable.refresh(this.queryParam)
    },
    // 启用/禁用用户
    onStatusChange(row) {
      const params = {}
      params.roleId = row.roleId
      params.status = row.status
      let text = '禁用'
      if (params.status == '1') {
        text = '启用'
      }
      setTimeout(() => {
        this.$http.post(editRoleStatus, params).then(() => {
          modal.info({title: '成功提示', content: text + '成功'})
        }).catch(() => {
        })
      }, 200)
    },
    addRole() {
      this.clearRadioRowEevnt()
      this.modalTitle = '新增角色信息'
      this.visible = true
    },
    editRole() {
      if (this.selectRow && this.selectRow.fixed == '1') {
        if (this.selectRow) {
          this.modalTitle = '修改角色信息'
          this.visible = true
        } else {
          modal.warn({title: '提示', content: '请先选择需要修改的数据'})
        }
      } else {
        modal.warn({title: '提示', content: '您没有修改该角色相关信息的权限'})
      }
    },
    saveRole() {
      // 表单验证
      const {$refs: {rolePage}} = this
      if (rolePage.checkForm()) {
        const role = rolePage.form
        if (role.roleId) {
          setTimeout(() => {
            this.$http.post(editRole, role).then((res) => {
              modal.info({title: '成功提示', content: '修改成功'})
              this.visible = false
              let row = res.result
              this.$refs.roleTable.updateRow(row)
              this.selectRow = row
              this.roleId = row.roleId
              this.$refs.roleTable.setRadioRow(row)
              this.$refs.roleTable.setCurrentRow(row)
            }).catch(() => {
            })
          }, 200)
        } else {
          setTimeout(() => {
            this.$http.post(addRole, role).then((res) => {
              modal.info({title: '成功提示', content: '新增成功'})
              this.visible = false
              this.queryParam.roleName = res.result.roleName
              this.findRoleList()
            }).catch(() => {
            })
          }, 200)
        }
      }
    },
    cancelRole() {

      this.visible = false
    },
    deleteRole() {
      if (this.selectRow && this.selectRow.fixed == '1') {
        if (this.selectRow) {
          const params = {}
          params.roleId = this.selectRow.roleId
          setTimeout(() => {
            this.$http.post(deleteRole, params).then(() => {
              modal.info({title: '成功提示', content: '删除用户成功'})
              this.refreshList()
            }).catch(() => {
            })
          }, 100)
        } else {
          modal.warn({title: '提示', content: '请先选择需要删除的数据'})
        }
      } else {
        modal.warn({title: '提示', content: '您没有修改该角色相关信息的权限'})
      }
    },
    closeRoleUser() {
      this.roleUserVisible = false
    },
    openRoleUserModel() {
      // 打开添加用户页面
      if (this.selectRow) {
        this.roleId = this.selectRow.roleId
        this.saveUserDisable = false
        this.deleteUserDisable = true
        this.roleUserVisible = true
      } else {
        modal.warn({title: '提示', content: '请先选择需要操作的角色'})
      }
    },
    saveUser() {
      const users = this.$refs.roleUserPage.$refs.userListTable.getAllCheckboxRecords()
      const roleId = this.selectRow.roleId
      if (users) {
        if (users.length <= 0) {
          modal.warn({title: '提示', content: '请先勾选需要授权的用户'})
          return false
        }
      } else {
        modal.warn({title: '提示', content: '请先勾选需要授权的用户'})
        return false
      }
      const roleFixedVOList = []
      users.forEach((item) => {
        let obj = {}
        obj.userId = item.userId
        obj.fixed = item.fixed
        roleFixedVOList.push(obj)
      })
      const params = {}
      params.roleId = roleId
      params.roleFixedVOList = roleFixedVOList
      setTimeout(() => {
        this.$http.post(saveRoleUser, params).then(() => {
          modal.info({title: '成功提示', content: '授权成功'})
          this.$refs.roleUserPage.findUserList()
          this.$refs.roleUserPage.clearUserChecked()
        }).catch(() => {
        })
      }, 10)
    },
    deleteUser() {
      if (this.selectRow) {
        const checkedUser = this.$refs.roleUserPage.$refs.userListTable.getAllCheckboxRecords()
        if (checkedUser && checkedUser.length > 0) {
          const userIds = []
          checkedUser.forEach((item) => {
            userIds.push(item.userId)
          })
          const params = {}
          params.userIds = userIds
          params.roleId = this.selectRow.roleId
          setTimeout(() => {
            this.$http.post(deleteRoleUser, params).then(() => {
              modal.info({title: '成功提示', content: '删除成功'})
              this.$refs.roleUserPage.findUserList()
              this.$refs.roleUserPage.clearCheck()
            }).catch(() => {
            })
          }, 10)
        } else {
          modal.warn({title: '提示', content: '请先勾选需要删除的用户'})
        }
      } else {
        modal.warn({title: '提示', content: '请先选择需要操作的角色'})
      }
    },
    setRoleUserBtn(value) {
      if (value) {
        if (value === '1') {
          this.saveUserDisable = false
          this.deleteUserDisable = true
        } else if (value === '2') {
          this.saveUserDisable = true
          this.deleteUserDisable = false
        }
        if (value === '3') {
          this.saveUserDisable = true
          this.deleteUserDisable = true
        }
      } else {
        this.saveUserDisable = false
        this.deleteUserDisable = true
      }
    },
    openRoleOrgModel() {
      if (this.selectRow && this.selectRow.fixed == '1') {
        // 打开组织授权页面
        if (this.roleId) {
          this.roleOrgVisible = true
        } else {
          modal.warn({title: '提示', content: '请先选择需要操作的角色'})
        }
      } else {
        modal.warn({title: '提示', content: '您没有修改该角色相关信息的权限'})
      }
    },
    saveOrg() {
      if (this.roleId) {
        const checkedObject = this.$refs.orgTreePage.checkedOrgKeys
        const params = {}
        if (checkedObject.checked) {
          const checkedkeys = checkedObject.checked;
          params.orgIds = checkedkeys;
        } else {
          params.orgIds = checkedObject;
        }
        params.roleId = this.roleId
        setTimeout(() => {
          this.$http.post(saveRoleOrg, params).then(() => {
            modal.info({title: '成功提示', content: '授权成功'})
            this.roleOrgVisible = false
          }).catch(() => {
          })
        }, 10)
      } else {
        modal.warn({title: '提示', content: '请先选择需要操作的角色'})
      }
    },
    openRoleRouterFuncModel() {
      if (this.selectRow && this.selectRow.fixed == '1') {
        // 打开资源授权页面
        if (this.roleId) {
          this.roleRouterFuncVisible = true
        } else {
          modal.warn({title: '提示', content: '请先选择需要操作的角色'})
        }
      } else {
        modal.warn({title: '提示', content: '您没有修改该角色相关信息的权限'})
      }
    },
    saveRouterFunc() {
      if (this.roleId) {
        const checkedkeys = this.$refs.routerFuncTreePage.checkedKeys
        const params = {}
        if (Array.isArray(checkedkeys)) {
          params.objectIds = checkedkeys
        } else {
          params.objectIds = checkedkeys.checked
        }

        params.roleId = this.roleId
        setTimeout(() => {
          this.$http.post(saveRoleRouterFunc, params).then(() => {
            modal.info({title: '成功提示', content: '授权成功'})
            this.roleRouterFuncVisible = false
          }).catch(() => {
          })
        }, 10)
      } else {
        modal.warn({title: '提示', content: '请先选择需要操作的角色'})
      }
    },
    openFlowNodeModel() {
      if (this.selectRow && this.selectRow.fixed == '1') {
        // 打开资源授权页面
        if (this.roleId) {
          this.flowNodeVisible = true
        } else {
          modal.warn({title: '提示', content: '请先选择需要操作的角色'})
        }
      } else {
        modal.warn({title: '提示', content: '您没有修改该角色相关信息的权限'})
      }

    },

    saveFlowNode() {
      if (this.roleId) {
        const checkedkeys = this.$refs.flowNodeTreePage.checkedKeys
        const params = {}
        if (Array.isArray(checkedkeys)) {
          params.objectIds = checkedkeys
        } else {
          params.objectIds = checkedkeys.checked
        }
        params.roleId = this.roleId
        setTimeout(() => {
          this.$http.post(saveRoleFlowNode, params).then(() => {
            modal.info({title: '成功提示', content: '授权成功'})
            this.flowNodeVisible = false
          }).catch(() => {
          })
        }, 10)
      } else {
        modal.warn({title: '提示', content: '请先选择需要操作的角色'})
      }
    },
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
<style lang="less" scoped>

</style>
